import { createI18n } from "vue-i18n";
import { LangStorage } from "@/storage/lang.storage";
import { LANG_VALUE } from "@/constants/language";
import ENConf from "./en";
import ZHConf from "./zh";
import type { App } from "vue";

export const getLanguage = () => {
  const languageCache = LangStorage.getLanguage();
  if (languageCache) {
    return languageCache;
  }

  // 没有选择语言
  const language = navigator.language.toLowerCase();
  const locales = [LANG_VALUE.En, LANG_VALUE.Zh];

  for (const locale of locales) {
    if (language.indexOf(locale) > -1) {
      return locale;
    }
  }
  return LANG_VALUE.Zh;
};

export const i18n = createI18n({
  legacy: false,
  locale: getLanguage(),
  messages: {
    [LANG_VALUE.Zh]: ZHConf,
    [LANG_VALUE.En]: ENConf,
  },
});

export const setupI18n = (app: App) => {
  app.use(i18n);
};

export const setLocale = (locale: LANG_VALUE) => {
  i18n.global.locale.value = locale;
  LangStorage.setLanguage(locale);
};
